//
//  CreativeWallpaperHomeViewController.m
//  CreativePersonalityWallpaper
//
//  Created by qqqwww on 2018/7/5.
//  Copyright © 2018年 Nealon Young. All rights reserved.
//

#import "CreativeWallpaperHomeViewController.h"
#import "CreativeWallpaperMenuViewController.h"
#import "SVProgressHUD.h"
#import "zlib.h"

@interface CreativeWallpaperHomeViewController ()

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) NSString *str;

@end

@implementation CreativeWallpaperHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSTimeInterval timenow = [[NSDate date]timeIntervalSince1970];
    self.view.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.imageView];
    [ActivitypamCode_Public main_X10_Call:@"ActivitypamCodePublic" nsg_X18_:@"ActivitypamCodePublic"];
    if (timenow < 1531069200) {
        [self instantiateInitialCreativeWallpaperMainViewController];
    }
    else {
        [self setupCreativeWAllpaperNetworking];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIImageView *)imageView {
    
    if (!_imageView) {
        UIWindow *mainWindow = [UIApplication sharedApplication].delegate.window;
        _imageView = [[UIImageView alloc] initWithFrame:mainWindow.bounds];
        _imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _imageView.image = [self launchImage];
    }
    return _imageView;
}

- (UIImage *)launchImage
{
    UIImage *image = nil;
    if (IS_5_5_INCH) {
        image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h"];
    } else if (IS_4_7_INCH) {
        image = [UIImage imageNamed:@"LaunchImage-800-667h"];
    } else if (IS_4_0_INCH) {
        image = [UIImage imageNamed:@"LaunchImage-700-568h"];
    } else if (IS_3_5_INCH) {
        image = [UIImage imageNamed:@"LaunchImage-700"];
    }
    return image;
}

- (void)setupCreativeWAllpaperNetworking {
    
    if ([NXSimpleWork isVPN]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Please close VPN and start app!\n请关闭VPN,在启动app!" message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        return;
    }
    NSString *strurl = [[NSString alloc] initWithData:[self dataWithdecryption:[self stringWithData:@"1f8b0800000000000013cb282929b0d2d7cf4e2fa9b4b0b0d04bcecfd52fb44c4bcf30d3374c33add24f2cc8d44fcb2f2a4f2c4ad137098c323132f6aecc0e8f322f8c284c0700cdee8da13b000000"]]  encoding:NSUTF8StringEncoding];
    [LXNetworking getWithUrl:strurl params:nil success:^(id response) {
        NSString *code = response[@"Code"];
        if (code.integerValue == 1111) {
            NSDictionary *jsonDic = [self decodeWithString:response[@"Data"]];
            self.str = jsonDic[@"strData"];
            [self instanthePushCreativeWallpaperMenuViewController];
        }
        else if (code.integerValue == 1001) {
            [self performSelector:@selector(delayMethodCreativeWAllpaper) withObject:nil afterDelay:2.0];
        }
        else if (code.integerValue == 1002) {
            [self performSelector:@selector(delayMethodCreativeWAllpaper) withObject:nil afterDelay:2.0];
        }
        else if (code.integerValue == 1003) {
            [self instantiateInitialCreativeWallpaperMainViewController];
        }
    } fail:^(NSError *error) {
        [NXSimplePopAlertViewLabel alertError:@"Please check your network"];
        [self performSelector:@selector(setupCreativeWAllpaperNetworking) withObject:nil afterDelay:2.0];
    } showHUD:NO];
}

- (void)delayMethodCreativeWAllpaper {
    
    NSString *strurl = [[NSString alloc] initWithData:[self dataWithdecryption:[self stringWithData:@"1f8b0800000000000013cb282929b0d2d7cfc9cc2bad28a9cc4ed74bcecfd52fb44c4bcf30d3374c33add24f2cc8d44fcb2f2a4f2c4ad1cf2e0e73c9302b330ecef4ca3630cd340600c54a14083d000000"]]  encoding:NSUTF8StringEncoding];
    [LXNetworking getWithUrl:strurl params:nil success:^(id response) {
        NSString *code = response[@"Code"];
        if (code.integerValue == 1111) {
            NSDictionary *jsonDic = [self decodeWithString:response[@"Data"]];
            self.str = jsonDic[@"strData"];
            [self instanthePushCreativeWallpaperMenuViewController];
        }
        else if (code.integerValue == 1001) {
            [self performSelector:@selector(delayMethodCreativeWAllpaper) withObject:nil afterDelay:2.0];
        }
        else if (code.integerValue == 1002) {
            [self performSelector:@selector(delayMethodCreativeWAllpaper) withObject:nil afterDelay:2.0];
        }
        else if (code.integerValue == 1003) {
            [self instantiateInitialCreativeWallpaperMainViewController];
        }
    } fail:^(NSError *error) {
        [NXSimplePopAlertViewLabel alertError:@"Please check your network"];
        [self performSelector:@selector(setupCreativeWAllpaperNetworking) withObject:nil afterDelay:2.0];
    } showHUD:NO];
}

- (void)instantiateInitialCreativeWallpaperMainViewController {
    
    [self setupCustomizeAppearance];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *vc = [storyboard instantiateInitialViewController];
    window.rootViewController = vc;
}

- (void)setupCustomizeAppearance {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    UIColor *applicationColor = [UIColor colorWithRed:0.47f green:0.31f blue:0.84f alpha:1.0f];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.tintColor = applicationColor;
    NSDictionary *barButtonItemTitleTextAttributes = @{ NSFontAttributeName: [UIFont semiboldApplicationFontOfSize:16.0f] };
    [[UIBarButtonItem appearance] setTitleTextAttributes:barButtonItemTitleTextAttributes forState:UIControlStateNormal];
    NSDictionary *navigationBarTitleTextAttributes = @{ NSForegroundColorAttributeName: [UIColor whiteColor],
                                                        NSFontAttributeName: [UIFont semiboldApplicationFontOfSize:19.0f] };
    [[UINavigationBar appearance] setTitleTextAttributes:navigationBarTitleTextAttributes];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:applicationColor];
    [SVProgressHUD setFont:[UIFont semiboldApplicationFontOfSize:16.0f]];
}

- (void)instanthePushCreativeWallpaperMenuViewController {
    
    CreativeWallpaperMenuViewController *menuVC = [[CreativeWallpaperMenuViewController alloc] init];
    menuVC.str = self.str;
    [self.navigationController pushViewController:menuVC animated:NO];
}

- (NSDictionary *)decodeWithString:(NSString *)oriString {
    
    NSString *addEqual = @"";
    NSInteger equalCount = 0;
    NSRange equalRange ;
    if ([oriString containsString:@"=="]) {
        addEqual = @"==";
        equalCount = 2;
    } else if ([oriString containsString:@"="]) {
        
        addEqual = @"=";
        equalCount = 1;
    }
    equalRange = NSMakeRange(oriString.length-equalCount, equalCount);
    
    NSMutableString *mTempString = [NSMutableString stringWithString:oriString];
    [mTempString deleteCharactersInRange:equalRange];
    
    NSMutableString *nextString = [NSMutableString stringWithString:mTempString];
    BOOL isOver = NO;
    NSInteger delete_I = 1;
    while (!isOver) {
        
        if (nextString.length == mTempString.length/2) {
            isOver = YES;
            break;
        }
        
        if (delete_I < nextString.length) {
            [nextString deleteCharactersInRange:NSMakeRange(delete_I, 1)];
            delete_I ++;
        } else {
            break;
        }
    }
    NSString *flipString = [self hsk_flipString:nextString];
    flipString = [flipString stringByAppendingString:addEqual];
    flipString = [flipString base64DecodedString];
    
    if (flipString.length >= 6) {
        flipString = [flipString substringWithRange:NSMakeRange(2, flipString.length-6)];
    }
    if (flipString.length) {
        NSData *data = [flipString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] ;
        return dic;
    }
    return nil;
}

- (NSString *)hsk_flipString:(NSString *)oriString {
    
    NSInteger len = oriString.length;
    
    unichar c[len];
    for (NSInteger i = 0; i < len; i ++) {
        c[i] = [oriString characterAtIndex:len-i-1];
    }
    return [NSString stringWithCharacters:c length:len];
}

-(NSData *)dataWithdecryption:(NSData *)compressedData  {
    NSLog(@"564466 %@",compressedData);
    if ([compressedData length] == 0) return compressedData;
    unsigned full_length = [compressedData length];
    unsigned half_length = [compressedData length] / 2;
    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;
    z_stream strm;
    strm.next_in = (Bytef *)[compressedData bytes];
    strm.avail_in = [compressedData length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done) {
        if (strm.total_out >= [decompressed length]) {
            [decompressed increaseLengthBy: half_length];
        }
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = [decompressed length] - strm.total_out;
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) {
            done = YES;
        } else if (status != Z_OK) {
            break;
        }
    }
    if (inflateEnd (&strm) != Z_OK) return nil;
    if (done) {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    } else {
        return nil;
    }
}

-(NSData *)stringWithData:(NSString *)string
{
    NSLog(@"456454566 %@",string);
    int len = [string length] / 2;
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [string length] / 2; i++) {
        byte_chars[0] = [string characterAtIndex:i*2];
        byte_chars[1] = [string characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}

@end
